package com.sqfw.project.community.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.sqfw.common.constant.HttpStatus;
import com.sqfw.framework.web.domain.AjaxResult;
import com.sqfw.project.community.domain.vo.WxLoginVO;
import com.sqfw.project.community.service.CommunityService;
import com.sqfw.project.system.domain.SysDept;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.system.mapper.SysDeptMapper;
import com.sqfw.project.system.mapper.SysUserMapper;
import com.sqfw.project.system.service.ISysUserService;
import com.sqfw.project.utils.AESUtils;
import com.sqfw.project.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CommunityServiceImpl implements CommunityService {

    /**
     * 微信授权apiUrl
     */
    @Value("${smgp.apiUrl}")
    private String smgpApiUrl;

    /**
     * 微信授权接口 加密的秘钥
     */
    @Value("${smgp.sqfwKey}")
    private String sqfwKey;

    private static final String WX_LOGIN = "/communityApi/getWxUserInfo";

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysDeptMapper deptMapper;



    @Override
    public Map<String, Object> wxLogin(WxLoginVO wxLoginVO) {
        Map<String, Object> userInfo = new HashMap<>(32);
        SysUser user = new SysUser();
        user.setPhonenumber(wxLoginVO.getPhone());
        List<SysUser> sysUserList =  userMapper.selectUserList(user);
        if (CollectionUtils.isEmpty(sysUserList)) {
            return null;
        }
        // 社区中心人员可以查询全部数据:community--社区中心人员； unit--承办单位人员
        userInfo.put("miniType", "community");
        SysUser sysUser = sysUserList.get(0);
        // 承办单位的人员只查询该部门的数据
        List<SysDept> deptList = deptMapper.selectChildrenDeptById(1L);
        for (SysDept sysDept : deptList) {
            if (String.valueOf(sysDept.getDeptId()).equals(String.valueOf(sysUser.getDeptId()))) {
                userInfo.put("miniType", "unit");
                userInfo.put("unitId", sysUser.getDeptId());
                break;
            }
        }
        userInfo.put("realName", sysUser.getNickName());
        return userInfo;
    }

    @Transactional
    @Override
    public Map<String, Object> getWxUserInfo(WxLoginVO wxLoginVO) {
        Map<String, String> headerParam = new HashMap<>(5);
        headerParam.put("token", getToken(System.currentTimeMillis(), sqfwKey));
        Map<String, String> params = setParams(wxLoginVO);
        log.info("获取微信openId：{}", params.toString());
        log.info("获取微信openId-url: {}", smgpApiUrl + WX_LOGIN);
        String result = HttpClientUtils.postJson(smgpApiUrl + WX_LOGIN, headerParam, params, null);
        log.info("获取微信openId返回 result : {}", result);
        if (StringUtils.isBlank(result)) {
            log.info("获取微信openId-失败");
            return null;
        } else {
            JSONObject resJson = JSONObject.parseObject(result);
            // 获取微信openId成功
            if (String.valueOf(HttpStatus.SUCCESS).equals(resJson.getString(AjaxResult.CODE_TAG))) {
                JSONObject dataJson = JSONObject.parseObject(resJson.getString(AjaxResult.DATA_TAG));
                Map<String, Object> userInfo = new HashMap();
                String openId = dataJson.get("openId").toString();
                userInfo.put("openId", openId);
                userInfo.put("nickName", dataJson.get("nickName"));
                userInfo.put("gender", dataJson.get("gender"));
                userInfo.put("city", dataJson.get("city"));
                userInfo.put("province", dataJson.get("province"));
                userInfo.put("country", dataJson.get("country"));
                userInfo.put("avatarUrl", dataJson.get("avatarUrl"));
                userInfo.put("unionId", dataJson.get("unionId"));
                // 根据openId查询
                if (StringUtils.isNotBlank(openId)) {
                    SysUser user = new SysUser();
                    user.setPhonenumber(wxLoginVO.getPhone());
                    // 正在授权的手机号
                    List<SysUser> sysUserList =  userMapper.selectUserList(user);
                    if (CollectionUtils.isEmpty(sysUserList)) {
                        return null;
                    }
                    SysUser myUser = sysUserList.get(0);
                    // 之前授权的手机号
                    SysUser sysUser = userMapper.getUserByWxOpenId(openId);
                    if (sysUser != null) {
                        // 如果手机号相同，同一个用户授权
                        // 如果手机号不同，说明换了手机号
                        if (!wxLoginVO.getPhone().equals(sysUser.getPhonenumber())) {
                            userMapper.updateUserWxOpenId(sysUser.getUserId());
                            SysUser updateUser = new SysUser();
                            updateUser.setUserId(myUser.getUserId());
                            updateUser.setWxOpenId(openId);
                            userMapper.updateUser(updateUser);
                        }
                    }else { // 根据openid没有查询到，第一次授权登录
                        SysUser updateUser = new SysUser();
                        updateUser.setUserId(myUser.getUserId());
                        updateUser.setWxOpenId(openId);
                        userMapper.updateUser(updateUser);
                    }
                }
                return userInfo;
            } else {
                return null;
            }
        }
    }

//    public Map<String, Object> getMap(WxLoginVO wxLoginVO) {
//        Map<String, Object> userInfo = new HashMap();
//        String openId = "o-Wbz5DWIbs2Kqjll85j-YlJVfbo";
//        userInfo.put("openId", openId);
//        userInfo.put("nickName", "洪磊");
//        userInfo.put("gender", "");
//        userInfo.put("city", "");
//        userInfo.put("province", "");
//        userInfo.put("country", "");
//        userInfo.put("avatarUrl", "");
//        userInfo.put("unionId", "");
//        // 根据openId查询
//        if (StringUtils.isNotBlank(openId)) {
//            SysUser user = new SysUser();
//            user.setPhonenumber(wxLoginVO.getPhone());
//            // 正在授权的手机号
//            List<SysUser> sysUserList =  userMapper.selectUserList(user);
//            if (CollectionUtils.isEmpty(sysUserList)) {
//                return null;
//            }
//            SysUser myUser = sysUserList.get(0);
//            // 之前授权的手机号
//            SysUser sysUser = userMapper.getUserByWxOpenId(openId);
//            if (sysUser != null) {
//                // 如果手机号相同，同一个用户授权
//                // 如果手机号不同，说明换了手机号
//                if (!wxLoginVO.getPhone().equals(sysUser.getPhonenumber())) {
//                    userMapper.updateUserWxOpenId(sysUser.getUserId());
//                    SysUser updateUser = new SysUser();
//                    updateUser.setUserId(myUser.getUserId());
//                    updateUser.setWxOpenId(openId);
//                    userMapper.updateUser(updateUser);
//                }
//            }else { // 根据openid没有查询到，第一次授权登录
//                SysUser updateUser = new SysUser();
//                updateUser.setUserId(myUser.getUserId());
//                updateUser.setWxOpenId(openId);
//                userMapper.updateUser(updateUser);
//            }
//        }
//        return userInfo;
//    }
//


    private Map<String, String> setParams(WxLoginVO wxLoginVO) {
        Map<String, String> params = new HashMap<>();
        params.put("encryptedData", wxLoginVO.getEncryptedData());
        params.put("iv", wxLoginVO.getIv());
        params.put("code", wxLoginVO.getCode());
        return params;
    }


    /**
     * 获取token, 根据时间加密：毫秒
     *
     * @param timestamp 时间戳：毫秒
     * @param key       秘钥
     * @return 加密好的token
     */
    private String getToken(Long timestamp, String key) {
        String token = AESUtils.encrypt(timestamp.toString(), key);
        return token;
    }
}
